package xyz.yinpeng.demo.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import xyz.yinpeng.demo.service.ProviderFeignService;
import xyz.yinpeng.demo.service.TestService;

/**
 * 主要展示服务调用方式
 * 1、通过负载均衡客户端获取服务IP和端口，组装服务地址，调用服务
 * 2、通过Feign（声明式的Web服务客户端定义方式）组件调用服务
 */
@Slf4j
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private ProviderFeignService providerFeignService;

    /**
     * 需要在RestTemplate配置中增加@LoadBalanced注解
     * @param name
     * @return
     */
    public Object sayHello1(String name) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String data = "{\"name\": \"" + name + "\"}";
        HttpEntity<String> requestEntity = new HttpEntity<>(data, headers);
        String response = restTemplate.postForObject("http://provider-service/provider/test", requestEntity, String.class);
        return response;
    }

    /**
     * 不可在RestTemplate配置中增加@LoadBalanced注解
     * @param name
     * @return
     */
    public Object sayHello2(String name) {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("provider-service");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/provider/test";
        log.info("请求URL：{}", url);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String data = "{\"name\": \"" + name + "\"}";
        HttpEntity<String> requestEntity = new HttpEntity<>(data, headers);
        String response = restTemplate.postForObject(url, requestEntity, String.class);
        return response;
    }

    public Object sayHello3(String name) {
        ProviderFeignService.SayHelloReq params = new ProviderFeignService.SayHelloReq();
        params.setName(name);
        String response = providerFeignService.sayHello(params);
        return response;
    }

}
